package com.huang.wangpan.controller;


import com.huang.wangpan.dao.FileDao;
import com.huang.wangpan.vo.Upfile;
import com.huang.wangpan.utils.ByteUnitConversion;
import com.huang.wangpan.utils.FileUtil;
import com.huang.wangpan.utils.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileController {
    @Autowired
    FileDao fileDao;
    @Autowired
    Upfile upfile;
    @Value("${file.warehouse}")
    private String fileWarehouse;

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @RequestMapping("/upload")
    public void upload(@RequestParam("file") MultipartFile file) {
        logger.info("FileController-->/upload 上传我来了");
        try {
            if (file.isEmpty()) {
                logger.warn("FileController-->/upload 文件为空");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            String size = new ByteUnitConversion().readableFileSize(file.getSize());
            upfile.setFilesize(size);
            upfile.setRealpath(FileUtil.getCurrentPath() + fileWarehouse + fileName);
            fileDao.insert(upfile);
            logger.info("上传的文件名为：{}", fileName);
            // 获取文件的后缀名
            int lastIndexOf = fileName.lastIndexOf(".");
            if (lastIndexOf > 0) { // 防止索引越界异常
                String suffixName = fileName.substring(lastIndexOf);
                logger.info("文件的后缀名为：{}", suffixName);
            }
            // 设置文件存储路径
            String filePath = FileUtil.getCurrentPath() + fileWarehouse + fileName;
            logger.info("文件存储路径: {}", filePath);

            File dest = new File(filePath);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }

            // file.transferTo(dest);// 文件写入

            // ##########方式二############
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath);
            Files.write(path,bytes);
            // ##########方式二############

            logger.info("FileController-->/upload 上传成功结束~");
        } catch (IllegalStateException | IOException e) {
            logger.error("FileController-->/upload error!!!", e);
        }
    }

    @RequestMapping("/getMD5")
    public void getMD5(HttpServletResponse response, HttpServletRequest request) {
        String MD5 = request.getParameter("MD5");
        ResultData rd = new ResultData();
        logger.info("/getMD5:MD5={}", MD5);
        Upfile file = null;
        file = fileDao.searchFileBymd5(MD5);
        if (file == null) {
            upfile.setMd5(MD5);
            rd.setData("yes");
            rd.writeToResponse(response);
        } else {
            rd.setData("no");
            rd.writeToResponse(response);
        }
    }

    @RequestMapping("/download*")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String path = FileUtil.getCurrentPath() + fileWarehouse;
        String filename = request.getParameter("filename");
        String currentpath = request.getParameter("currentpath");
        logger.info("当前文件路径为: {}", currentpath);
        logger.info("下载的文件为: {}", filename);
        File file = new File(path + filename);
        doDownload(response, file);
    }

    public void doDownload(HttpServletResponse response, File file) {
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            String fileName = null;// 解决中文文件名问题
            try {
                fileName = URLEncoder.encode(file.getName(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("FileController-->doDownload error!!! {} 包含中文文件名", file.getName(), e);
            }
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
